import {
	loadModules
} from "../../common/loadModules.js"

import {
	baseServers
} from "../../common/config.js"

import {
	getMapLayers
} from "../../utils/getLayersByConfig.js"

class CreateMap {
	viewId = null
	Arcgis = {} // arcgis 原生加载的类
	viewer = null // 全局viewer视图
	_config = {} // json配置

	constructor(_config, id = 'arcigs_01') {
		this._config = _config
		this.viewId = id
	}

	// 创建视图
	initViewer() {
		return new Promise(async (resolve, reject) => {
			let {
				wkid,
				extent,
				minZoom,
				maxZoom,
			} = this._config?.mapConfig || {}
			try {
				// 加载arcgis方法类
				this.Arcgis = await loadModules()

				let {
					Map,
					MapView,
					Extent,
				} = this.Arcgis
				// 创建视图
				const map = new Map();
				this.viewer = new MapView({
					container: this.viewId,
					map,
					constraints: {
						minZoom,
						maxZoom
					},
					spatialReference: {
						wkid
					},
				});

				if (!this.viewer) return reject({
					msg: '地图加载异常'
				})

				// 设置地图初始位置，例如你想让你的地图初始显示呼和浩特
				if (extent) this.viewer.extent = new Extent(extent);

				this.#_addDefLayers()

				resolve(this.viewer)
			} catch (err) {
				console.log(err);
				reject(err)
			}
		})
	}

	// 加载默认服务 - 私有方法
	#_addDefLayers() {
		// 默认服务
		let defaultServer = this._config?.defaultServer || {}
		let serverKeys = Object.keys(defaultServer).filter(key => defaultServer[key])
		let servers = baseServers.filter(item => serverKeys.includes(item.id))
		// 配置文件中的服务
		let servers2 = (this._config?.layerConfig || []).map(item => {
			if (item.useBaseUrl) item.url = (this._config?.baseUrl || '') + item.url
			return item
		})

		let layers = getMapLayers({
			layers: servers.concat(servers2),
			Arcgis: this.Arcgis
		})
		console.log(layers, 'layerslayers');
		this.viewer.map.addMany(layers)
	}
}

export default CreateMap